package com.whnk.pm.util;

import com.whnk.common.config.Global;
import org.apache.commons.collections4.CollectionUtils;

import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import static org.jsoup.nodes.Entities.EscapeMode.base;

public class FileUtil {

    public static File downloadFile(String fileType, String fileName, byte[] bytes) throws IOException {
        File file = new File(Global.getDownloadPath()+ fileType + "-" + fileName);
        if (!file.exists()) {
            file.createNewFile();
        } else {
            file.deleteOnExit();
        }
        try(OutputStream outputStream = new FileOutputStream(file);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream)) {
            bufferedOutputStream.write(bytes);
        }
        return file;
    }

    public static void zipFile(File resultFile, List<File> fileList) throws IOException {
        if (!resultFile.exists()) {
            resultFile.createNewFile();
        } else {
            resultFile.deleteOnExit();
        }
        try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(resultFile))) {
            if (CollectionUtils.isEmpty(fileList)) {
                out.putNextEntry(new ZipEntry(base + "/"));
            } else {
                for (File file : fileList) {
                    try (FileInputStream fos = new FileInputStream(file)) {
                        out.putNextEntry(new ZipEntry(file.getName()));
                        byte[] bytes = new byte[1024];
                        int len;
                        //将源文件写入到zip文件中
                        while ((len = fos.read(bytes)) != -1) {
                            out.write(bytes, 0 ,len);
                        }
                    }
                }
            }
        }
    }
}
